<?php
//创建websocket服务器对象，监听0.0.0.0:9502端口
$ws = new swoole_websocket_server("0.0.0.0", 9501);
           
$ws->set(
    [
         'worker_num' => 2 , // worker进程数，cpu 1-4倍
    	 'max_request' => 100,
    	 'daemonize' => 1,
    ]
);

//监听WebSocket连接打开事件
$ws->on('open', function ($ws, $request) {
    // var_dump($request->fd, $request->get, $request->server);
	$redis = new Redis();
	$redis->connect('127.0.0.1', 6379);
	$redis->auth('si1OCDvrr4WitsVi');
	$ws->redis = $redis;
});

//监听WebSocket消息事件
$ws->on('message', function (swoole_websocket_server $ws, $frame) {
    if(isset($frame->data)){
       $message =  json_decode($frame->data,true);
       switch ($message['type']) {
           case 'init':
               $ws->redis->set('user'.$message['id'],$frame->fd); 
               break;         
           case 'say':
               $client_id = $ws->redis->get('user'.$message['to']);
               $ws->push($client_id, $frame->data);
               break;
       }

    }
    
});

//监听WebSocket连接关闭事件
$ws->on('close', function ($ws, $fd) {
    echo "client-{$fd} is closed\n";
});

$ws->start();